package com.shxzz.easy12306.services.ticket.mq.consumer;

import cn.hutool.core.bean.BeanUtil;
import com.shxzz.easy12306.framework.starter.common.dto.order.CloseTicketOrderReqDTO;
import com.shxzz.easy12306.framework.starter.common.dto.order.TicketOrderItemCreateReqDTO;
import com.shxzz.easy12306.framework.starter.common.mq.base.MessageWrapper;
import com.shxzz.easy12306.framework.starter.common.mq.constant.OrderRocketMQConstant;
import com.shxzz.easy12306.framework.starter.common.mq.event.DelayCloseOrderEvent;
import com.shxzz.easy12306.framework.starter.convention.exceptions.ServiceException;
import com.shxzz.easy12306.framework.starter.convention.result.Result;
import com.shxzz.easy12306.services.ticket.common.constant.RocketMQConstant;
import com.shxzz.easy12306.services.ticket.dto.domain.SelectSeatDTO;
import com.shxzz.easy12306.services.ticket.remote.OrderRemoteService;
import com.shxzz.easy12306.services.ticket.service.SeatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 延迟关闭订单消息消费者
 *
 * @author shxzz
 * @create 2024-03-16-13:58
 */
@Slf4j
@RequiredArgsConstructor
@Component
@RocketMQMessageListener(
        topic = OrderRocketMQConstant.DELAY_CLOSE_ORDER_TOPIC,
        selectorExpression = OrderRocketMQConstant.DELAY_CLOSE_ORDER_TAG,
        consumerGroup = RocketMQConstant.DELAY_CLOSE_ORDER_CG
)
public class DelayCloseOrderConsumer implements RocketMQListener<MessageWrapper<DelayCloseOrderEvent>> {

    private final OrderRemoteService orderRemoteService;
    private final SeatService seatService;

    @Override
    public void onMessage(MessageWrapper<DelayCloseOrderEvent> message) {

        DelayCloseOrderEvent delayCloseOrderEvent = message.getMessage();
        String orderSn = delayCloseOrderEvent.getOrderSn();
        log.info("消费,延时关闭订单，订单号：{}", orderSn);
        Result<Boolean> booleanResult = orderRemoteService.closeTicketOrder(new CloseTicketOrderReqDTO(orderSn));
        if (!booleanResult.isSuccess()) {
            throw new ServiceException("远程调用订单关闭失败");
        }
        if (Boolean.FALSE.equals(booleanResult.getData())) return;

        String trainId = delayCloseOrderEvent.getTrainId();
        String departure = delayCloseOrderEvent.getDeparture();
        String arrival = delayCloseOrderEvent.getArrival();
        List<TicketOrderItemCreateReqDTO> trainPurchaseTicketResults = delayCloseOrderEvent.getTrainPurchaseTicketResults();
        List<SelectSeatDTO> selectSeatDTOList = BeanUtil.copyToList(trainPurchaseTicketResults, SelectSeatDTO.class);
        seatService.rollbackSeatStatus(trainId, departure, arrival, selectSeatDTOList);
    }

}
